/****
 *  全局变量
 */
var port; //与tabs页面进行通信
var storage = { cookies: [] };
/**
 * 初始化连接信息
 */
var init = function () {
  /**
   * 查找当前激活的tab页面，建立消息通道
   */
  getCurrentTabId(tabId => {
    /**
     * 与当前打开的标签页通信
     * @param {*} tabId
     */
    port = chrome.tabs.connect(tabId, { name: 'test-connect' });
  })
  // 读取数据，第一个参数是指定要读取的key以及设置默认值
  chrome.storage.local.get(['cookies'], function (data) {
    console.log("storage 内容：", data);
    storage = data || {};
    setCookiePopupList(storage.cookies);
  });
  // 监听获取cookie 按钮点击
  document.getElementById('get-tab').addEventListener('click', function () {
    port.postMessage({ type: 'get-cookie' });
    port.onMessage.addListener(function (msg) {
      switch (msg.type) {
        case 'msg': notifications(msg.data); break;
        case 'save-cookie': saveCurrentCookie(msg.data);
        default: return;
      }

    });
  })
  // 调用background的方法
  document.getElementById('call-background').addEventListener('click', function () {
    var bg = chrome.extension.getBackgroundPage();
    bg.messageHandler();
  })
  /**
   * 清空按钮事件绑定
   */
  document.getElementById('clear').addEventListener('click', function () {
    storage.cookies = [];
    setCookiePopupList(storage.cookies);
    chrome.storage.local.set({ 'cookies': storage.cookies }, function () {
      console.log('保存成功！');
    });

  })
}

init();



/**
 * 获取当前正在运行的标签页id
 * @param {*} callback
 */
function getCurrentTabId(callback) {
  chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
    if (callback) callback(tabs.length ? tabs[0].id : null);
  });
}
/**
 * 简易的消息通知
 * @param {*} msg
 */
var notifications = function (message) {
  chrome.notifications.create(null, {
    type: 'image',
    iconUrl: 'avatar.png',
    title: '通知',
    message,
    imageUrl: 'avatar.png'
  });
}



/**
 * 将当前页面的cookie信息保存到chome.storage
 * @param {*} msg
 */
var saveCurrentCookie = function (msg) {

  var cookies = storage.cookies || [];
  // 保存数据
  let index = cookies.findIndex(item => item.host == msg.host);
  if (index >= 0) {
    cookies[index] = msg;
  } else {
    cookies.push(msg)
  }
  chrome.storage.local.set({ 'cookies': cookies }, function () {
    console.log('保存成功！');
  });
  setCookiePopupList(cookies);
  notifications('cookie storage 等信息已经复制到粘贴板!');
}

/**
 * 将选择的cookie设置到当前域名下
 * @param {*} host
 */
var setCookieToCurrentPage = function (host) {
  console.log(`开始设置,${host}`);
  var data = storage.cookies.find(item => item.host == host)
  if (data) {
    port.postMessage({ type: 'set-cookie', data });
  }
}

// 修改已经保存的cookies列表
var setCookiePopupList = function (list = []) {
  var subList = document.querySelector('.sub-list');
  subList.innerHTML = '';
  list.forEach(item => {
    var li = document.createElement('li');
    // 显示文本
    var label = document.createElement('label');
    label.innerText = item.host;
    li.append(label);

    var span = document.createElement('span');
    span.innerText = '删除';
    li.append(span);

    subList.appendChild(li);
  })

}




/**
 * 从列表移除
 * @param {*} host
 */
var removeCookieFromList = function (host) {
  console.log(`开始设置,${host}`);
  var cookies = storage.cookies;
  var index = cookies.findIndex(item => item.host == host)
  if (~index) {
    cookies.splice(index, 1);
    setCookiePopupList(cookies);
    chrome.storage.local.set({ 'cookies': cookies }, function () {
      console.log('保存成功！');
    });
  }
}

// setCookiePopupList(storage.cookies);
/**
 * cookie 列表绑定点击事件
 */
var subList = document.querySelector('.sub-list');
subList.addEventListener('click', e => {
  if (e.target.nodeName == 'LABEL') {
    setCookieToCurrentPage(e.target.innerText);
  } else if (e.target.nodeName == 'SPAN') {
    removeCookieFromList(e.target.previousElementSibling.innerText);
  }
})


// console.log("hello popup")
// // 向页面注入JS
// function injectCustomJs(jsPath) {
//   jsPath = jsPath || 'inject/inject.js';
//   var temp = document.createElement('script');
//   temp.setAttribute('type', 'text/javascript');
//   // 获得的地址类似：chrome-extension://ihcokhadfjfchaeagdoclpnjdiokfakg/js/inject.js
//   temp.src = chrome.extension.getURL(jsPath);
//   temp.onload = function () {
//     // 放在页面不好看，执行完后移除掉
//     this.parentNode.removeChild(this);
//   };
//   document.head.appendChild(temp);
// }
// injectCustomJs();
